import React, { useState } from "react";
import { Form, Input, Button, message } from "antd";
import { CloseOutlined } from "@ant-design/icons";
import { userApi } from "../../api/services/user/user";
import type { RequestPasswordResetRequest, ResetPasswordRequest } from "../../api/dto/user";

interface ForgetPasswordProps {
  onBack: () => void; 
}

interface ForgetPasswordFormValues {
  email: string;
  code: string;
  newPassword: string;
  newPasswordConfirmation: string;
}

const ForgetPassword: React.FC<ForgetPasswordProps> = ({ onBack }) => {
  const [form] = Form.useForm<ForgetPasswordFormValues>();
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [resetting, setResetting] = useState(false);

  const isSuccessResponse = (code: number | string | undefined): boolean => {
    if (code === undefined) return false;
    return [0, 200, "0", "200"].includes(code as number | string);
  };

  const handleSendCode = async () => {
    try {
      const email = form.getFieldValue('email');
      if (!email) {
        message.error("请先输入邮箱地址");
        return;
      }

      const requestData: RequestPasswordResetRequest = {
        email: email
      };

      setSendingCode(true);
      const response = await userApi.requestPasswordReset(requestData);

      if (isSuccessResponse(response.code)) {
        message.success("验证码已发送，请查收邮箱");
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        message.error(response.message || response.msg || "发送验证码失败");
      }
    } catch (error) {
      console.error("发送验证码出错:", error);
      message.error("发送验证码失败，请稍后再试");
    } finally {
      setSendingCode(false);
    }
  };

  const handleResetPassword = async (values: ForgetPasswordFormValues) => {
    if (values.newPassword !== values.newPasswordConfirmation) {
      message.error("两次输入的密码不一致");
      return;
    }

    try {
      setResetting(true);
      const resetData: ResetPasswordRequest = {
        email: values.email,
        code: values.code,
        newPassword: values.newPassword,
        newPasswordConfirmation: values.newPasswordConfirmation
      };

      const response = await userApi.resetPassword(resetData);

      if (isSuccessResponse(response.code)) {
        message.success("密码重置成功！");
        onBack(); // 返回登录页面
      } else {
        message.error(response.message || response.msg || "密码重置失败");
      }
    } catch (error) {
      console.error("重置密码出错:", error);
      message.error("密码重置失败，请稍后再试");
    } finally {
      setResetting(false);
    }
  };

  return (
    <div className="fixed top-[0px] rounded-[8px] w-[400px] flex items-center justify-center bg-[#ffffff]">
      <div className="w-[300px] h-full relative p-[0px] mb-[10px]">
        <div className="flex flex-col items-center">
          <button
            onClick={onBack}
            className="absolute top-[20px] bg-transparent right-[-20px] z-10 text-[#A0AEC0] border-none"
          >
            <CloseOutlined />
          </button>
          <div className="pt-12">
            <div className="flex flex-col items-center mb-[15px]">
              <div>
                <img
                  src="https://makabaka7-x.github.io/Swust_UI_New/images/logo.png"
                  className="object-contain w-[50px] h-[50px] mb-[10px]"
                  alt="Logo"
                />
              </div>
              <h2 className="m-[0px] p-[0px]">找回密码</h2>
            </div>
            <div className="mt-[0px] py-[0px] mb-[15px] text-[#4a5568] leading-[1.5] px-[5px] break-keep">
              输入邮箱获取验证码重置密码
            </div>
          </div>
        </div>
        
        <Form<ForgetPasswordFormValues>
          form={form}
          layout="vertical"
          onFinish={handleResetPassword}
          requiredMark={false}
          size="middle"
          className="text-[14px] h-[420px]"
        >
          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              { required: true, message: "请输入邮箱地址" },
              { type: "email", message: "请输入有效的邮箱地址" }
            ]}
          >
            <Input placeholder="请输入邮箱地址" />
          </Form.Item>

          <Form.Item label="验证码">
            <div style={{ display: "flex", gap: "10px" }}>
              <Form.Item
                name="code"
                noStyle
                rules={[{ required: true, message: "请输入验证码" }]}
              >
                <Input placeholder="请输入验证码" style={{ flex: 1 }} />
              </Form.Item>
              <Button
                type="primary"
                onClick={handleSendCode}
                disabled={sendingCode || countdown > 0}
                style={{ width: "90px" }}
              >
                {countdown > 0 ? `${countdown}秒` : sendingCode ? "发送中..." : "获取"}
              </Button>
            </div>
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[{ required: true, message: "请设置新密码" }]}
          >
            <Input.Password placeholder="请设置新密码" />
          </Form.Item>

          <Form.Item
            label="确认密码"
            name="newPasswordConfirmation"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: "请确认密码" },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请再次输入新密码" />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={resetting}
              style={{ width: "100%", height: "45px" }}
            >
              重置密码
            </Button>
          </Form.Item>
        </Form>

        <div className="text-center mb-[10px] font-[400] text-[#566072]">
          记起密码了?
          <span className="text-[#3498DB] font-[500] cursor-pointer" onClick={onBack}>
            {" "}
            返回登录
          </span>
        </div>
      </div>
    </div>
  );
};

export default ForgetPassword;
